package com.tsinkai.ettp.controller.wx;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tsinkai.ettp.utils.HttpRequest;

@RestController
@RequestMapping(value="wx")
public class WxLoginController {
	
	@RequestMapping(value="login")
	public void login(HttpServletResponse resp) throws UnsupportedEncodingException {
		String redUrl = "http://fengcan.nat300.top/wx/redirect";
		
		 String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxcec14c0cd521b2cc"
	                + "&redirect_uri="+URLEncoder.encode(redUrl, "utf-8")
	                + "&response_type=code"
	                + "&scope=snsapi_userinfo"
	                + "&state=test#wechat_redirect";
		try {
			resp.sendRedirect(url);
		} catch (IOException e) {
			System.out.println("重定向失败");
			e.printStackTrace();
		}
	}
	@RequestMapping(value = "redirect")
	public String redirect(String code,String state) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
				+ "appid=wxcec14c0cd521b2cc"
				+ "&secret=51748903f3da3309a8c4ef5a1c2bd3ef"
				+ "&code="+code
				+ "&grant_type=authorization_code";
		String result = HttpRequest.doGet(url);
		System.out.println(result);
		JSONObject resultJson = new JSONObject(result);
		String accessToken = resultJson.getString("access_token");
		String openid = resultJson.getString("openid");
		System.out.println(accessToken);
		String userinfoUrl = "https://api.weixin.qq.com/sns/userinfo?"
				+ "access_token="+accessToken
				+ "&openid="+openid
				+ "&lang=zh_CN";
		String userinfoResult = HttpRequest.doGet(userinfoUrl);
		System.out.println(userinfoResult);
		JSONObject userinfoJson = new JSONObject(userinfoResult);
		String nickname = userinfoJson.getString("nickname");
		System.out.println(nickname);
		return nickname;
	}
}
